package com.wanghua.spring.test.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.junit.Test;

import java.lang.reflect.Modifier;

public class FastJsonDemo {
    class MyObj {
        public transient int x;
        @JSONField(serialize = false)  //此字段不会被序列化成json
        public int y;
        @JSONField(name = "aa")  //改名为aa
        public int a;
        public int b;

        public MyObj2 myObj2;

        public MyObj(){

        }

        public MyObj(int x, int y, int a, int b, MyObj2 myObj2) {
            this.x = x;
            this.y = y;
            this.a = a;
            this.b = b;
            this.myObj2 = myObj2;
        }
    }

    class MyObj2 {
        public int m;
        public int n;

        public MyObj myObj;

        public MyObj2(int m, int n, MyObj myObj) {
            this.m = m;
            this.n = n;
            this.myObj = myObj;
        }
    }


    @Test
    public void gson() {
        MyObj2 obj2 = new MyObj2(100, 200,null);
        MyObj obj3 = new MyObj(1, 2, 3, 4, obj2);
        obj2.myObj=obj3;
        String str = JSON.toJSONString(obj3);
        //String str = JSON.toJSONString(obj3, SerializerFeature.DisableCircularReferenceDetect);
        //默认是会启用循环引用的，如下：
        //{"aa":3,"b":4,"myObj2":{"m":100,"myObj":{"$ref":".."},"n":200}}
        //加了 “SerializerFeature.DisableCircularReferenceDetect”就不会了，但遇到循环引用会报错。

        obj2.myObj.myObj2=null;
        str = JSON.toJSONString(obj2);
        JSONObject jsonObject =JSON.parseObject(str);
        Integer a =jsonObject.getIntValue("m");
    }
}
